package com.zwy.customspinner

import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.ListPopupWindow
import android.widget.Spinner
import android.widget.Toast
import androidx.activity.ComponentActivity
import java.lang.reflect.Field


/**
 * 菜鸟教程：https://www.runoob.com/w3cnote/android-tutorial-spinner.html
 * Android原生Spinner修改背景样式与使用：https://blog.csdn.net/ningchao328/article/details/125912020
 * 更改spinner默认显示的字体颜色：https://blog.csdn.net/m0_38026190/article/details/105866270
 * Spinner下拉框使用：https://juejin.cn/post/6977629658879623181
 */
class MainActivity : ComponentActivity() {

    private var spinner: Spinner? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        spinner = findViewById(R.id.spinner)
        val array = arrayOf("AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ")
        val adapter = ArrayAdapter(this, R.layout.my_spinner_textview, array)

        spinner?.adapter = adapter
        spinner?.setSelection(0, true) //设置默认显示
        try {
            val popup: Field = Spinner::class.java.getDeclaredField("mPopup")
            popup.isAccessible = true

            // Get private mPopup member variable and try cast to ListPopupWindow
            val popupWindow = popup[spinner] as ListPopupWindow
            // Set popupWindow height to 200px
            popupWindow.height = 150
        } catch (e: NoClassDefFoundError) {
        } catch (e: ClassCastException) {
        } catch (e: NoSuchFieldException) {
        } catch (e: IllegalAccessException) {
        }
        spinner?.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                Toast.makeText(this@MainActivity, "position = $position", Toast.LENGTH_SHORT)
                    .show()
//                when (this@MainActivity.resources.getStringArray(R.array.status)[position]) {
//                    "关闭" -> {
//                        Toast.makeText(this@MainActivity, "关闭", Toast.LENGTH_SHORT)
//                            .show()
//                    }
//
//                    "向里开" -> {
//                        Toast.makeText(this@MainActivity, "向里开", Toast.LENGTH_SHORT)
//                            .show()
//                    }
//
//                    "向外开" -> {
//                        Toast.makeText(this@MainActivity, "向外开", Toast.LENGTH_SHORT)
//                            .show()
//                    }
//                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

    }
}
